package cn.evilelf.util;

import java.io.UnsupportedEncodingException;

import cn.evilelf.util.exceptions.InvalidOptionException;

public class Base64 {

	private static final String usage = "base64 <(-e -str <str>)|(-d -code <code>)>";

	public static void main(String[] args) {
		try {
			Options options = new Options(args);

			if (options.containsOption("e")) {
				encode(options.getOptionValue("str"));
			}

			else if (options.containsOption("d")) {
				decode(options.getOptionValue("code"), options
						.getOptionValue("encode"));
			} else {
				throw new InvalidOptionException();
			}
		} catch (InvalidOptionException e) {
			System.err.println("Invalid options, usage:");
			System.err.println(usage);
			System.err.flush();
			System.exit(1);
		}
	}

	private static void decode(String optionValue, String encode) {
		try {
			System.out.println(new String(Base64Coder.decode(optionValue),
					encode));
		} catch (UnsupportedEncodingException e) {
			System.err.println("Unsupported Encoding!");
			System.err.flush();
			System.exit(1);
		}

	}

	private static void encode(String optionValue) {
		System.out.println(Base64Coder.encodeString(optionValue));

	}

}
